package com.bdc.whatwhat.task;

import android.os.AsyncTask;

import com.bdc.whatwhat.Service.Service;

/**
 * Created by florentchampigny on 25/06/14.
 */
public class ConnexionTask extends AsyncTask<String,Void,String>{

    ConnexionTaskDelegate delegate;
    boolean erreurReseau;

    public ConnexionTask(ConnexionTaskDelegate delegate){
        this.delegate = delegate;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        if(delegate != null)
            delegate.afficherChargement(true);
    }

    @Override
    protected String doInBackground(String... strings) {
        String email = strings[0];
        String origin = strings[1];
        String id = strings[2];
        String token = strings[3];
        String nom = strings[4];
        String prenom = strings[5];
        String os = strings[6];
        String jeton = strings[7];
        try{
            return Service.connexion(email,origin,id,token, nom, prenom,os,jeton);
        }catch (Service.NetworkException e){
            erreurReseau = true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String token) {
        super.onPostExecute(token);
        if(delegate != null) {
            delegate.afficherChargement(false);
            if(token != null){
                delegate.onConnecte(token);
            }else {
                if(erreurReseau)
                    delegate.onErreurReseau();
                else
                    delegate.onErreurConnexion();
            }
        }
    }

    public interface ConnexionTaskDelegate{
        public void afficherChargement(boolean afficher);
        public void onConnecte(String token);
        public void onErreurConnexion();
        public void onErreurReseau();
    }
}
